package com.geekhole.demo.v3.application;

import com.geekhole.demo.application.UserApplication;
import com.geekhole.demo.domain.CreateAndEnableUserContext;
import com.geekhole.demo.domain.ModifyUserNameContext;
import com.geekhole.demo.domain.User;
import com.geekhole.demo.domain.UserNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

@Service
public class UserV3Application
        extends BaseV3Application<User>
        implements UserApplication {
    private final JpaRepository<User, Long> repository;
    @Autowired
    public UserV3Application(ApplicationEventPublisher eventPublisher, JpaRepository<User, Long> repository) {
        super(eventPublisher, repository);
        this.repository = repository;
    }

    @Override
    public void createAndEnableUser(CreateAndEnableUserContext cxt) {
        executeCreate(cxt,
                        context -> User.create(context.getName(), context.getAge()),
                        (createAndEnableUserContext, user) -> user.enable()
                );
    }

    @Override
    public void modifyUserName(ModifyUserNameContext cxt) {
        executeUpdate(cxt,
                    context -> repository.getById(context.getUserId()),
                    context -> {throw new UserNotFoundException(context.getUserId());},
                    (modifyUserNameContext, user) -> user.modifyUserName(modifyUserNameContext.getNewName())
                );
    }
}
